package cn.xianyang.basic.interceptor;

import cn.xianyang.basic.annotation.PreAuthorize;
import cn.xianyang.basic.jwt.JwtUtils;
import cn.xianyang.basic.jwt.LoginResult;
import cn.xianyang.basic.jwt.Payload;
import cn.xianyang.basic.jwt.RsaUtils;
import cn.xianyang.system.mapper.PermissionMapper;
import cn.xianyang.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;

/**
 * 登录拦截器
 */
@Component  //将此类标记为Spring容器中的一个Bean。
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;
    @Value("${rsa.pub}")
    private String publicKeyValue;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取 U-token
        String token = request.getHeader("U-TOKEN"); //修改后为JWT串
        //登陆,设置处理乱码请求
        response.setCharacterEncoding("utf-8");
        if (StringUtils.hasLength(token)){
            //根据U-token从redis中获取登录信息
            /*Object loginTmp = redisTemplate.opsForValue().get(token);*/
            //现在需要得到登录人和登录对应的权限，解密JWT串 ....获取共钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            //使用公钥去解密JWT串
            Payload<LoginResult> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginResult.class);
            //员工登录
            LoginResult loginResult = payload.getUserInfo();
            if (loginResult != null){
                //增加权限校验  == 登陆 成功后需要查看是否有权限去访问某个资源
                //判断是不是员工，是就需要验证权限
                Logininfo logininfo = loginResult.getLogininfo();
                if (logininfo.getType() == 0){ //0就是员工  1是用户
                    //得到当前请求的资源 url
                    HandlerMethod method = (HandlerMethod) handler;
                    //调取标记了注解，就要权限校验。。。没有打PreAuthorize的类就全是公共资源
                    PreAuthorize annotation = method.getMethodAnnotation(PreAuthorize.class);
                    if (annotation != null){
                        String currentSn = annotation.value();//本次请求的sn
                        //查询出当前登陆人拥有权限的资源 permissions
                        //List<String> permissions = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
                        //判断permissions是否包含 url
                        if (!loginResult.getPermissions().contains(currentSn)){
                            //不包含就提示权限不足，请联系管理者   noPermission没有权限
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;//阻止放行
                        }
                        //包含就放行
                    }
                }
                //刷新过期时间
                //redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
                return true; //登录了，放行
            }
        }

        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;//阻止放行
    }
}
